<template>
  <div>
    <div class="wrap" v-loading="loading">

      <w-s-socket v-if="isSocket"></w-s-socket>

      <shipment-info-view
        :data="data"
        :shipment-box="shipmentBox"
        :shipment-goods="shipmentGoods"
        :shipment-box-label-list="shipmentBoxLabelList"
        :container-id.sync="currentContainerId"
        @changeData="getData"
      ></shipment-info-view>

      <ShipmentInfoImg :data="data" :updateImgUrl="updateImgUrl" :saveFunc="saveShipmentImg" :getFunc="getShipmentImgArr"></ShipmentInfoImg>



      <div class="footer" style="margin-top: 30px" v-if="false">
        <el-button type="info" @click="goBack">{{$t('common.back')}}</el-button>
        <el-button type="primary" @click="checkConfirmNum" :disabled="checkConfirm" v-if="data.status === 0 && (!data.labelOrder || data.labelOrder.status === 2)" :loading="btnLoading">{{$t('shipment.Confirm receipt')}}</el-button>
        <el-button type="danger" @click="deliver" v-if="data.status === 1 && data.type === 1 && data.deliver === 0 && data.cancel === 0" :loading="btnLoading">{{$t('shipment.Confirm warehouse entry')}}</el-button>
        <export-shipment-a4 :shipment="data"></export-shipment-a4>
        <el-button v-if="data.status === 1" type="primary" @click="showPDFDialog(data)" :loading="jhLoading">{{$t('shipment.导出入库单')}}</el-button>
      </div>

      <el-dialog :title="$t('picking.exportTitle2')" :visible.sync="PDFDialog" width="400px">
        <div style="margin-top: -15px">
          <el-radio v-model="currentPDFForm.PDFType" :label="1" class="mgb10">{{$t('picking.exportRadio1')}}</el-radio>
          <br>
          <el-radio v-model="currentPDFForm.PDFType" :label="2">{{$t('picking.exportRadio2')}}</el-radio>
        </div>
        <div slot="footer" class="dialog-footer" style="margin-top: -15px">
          <el-button @click="PDFDialog = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="shipmentPDF" :loading="printLoading">{{ $t('common.confirm') }}</el-button>
        </div>
      </el-dialog>

    </div>

    <footer-nav>
      <el-button type="info" @click="goBack">{{$t('common.back')}}</el-button>
      <el-button type="primary" @click="confirmReceived" :loading="receivedLoading" v-if="data.status2 === WAIT_FL_RECEIVE() && isFirstLegRole()">确认接收</el-button>
      <el-button type="primary" @click="confirmWMReceived" :loading="receivedLoading" v-if="data.status2 === WAIT_RECEIVE() && data.planType === PLAN_TYPE_MW() && isInboundSortingRole()">确认已接收</el-button>
      <el-button type="primary" @click="confirmSorted" :loading="receivedLoading" v-if="data.status2 === WAIT_SORTING() && data.planType === PLAN_TYPE_MW() && isInboundSortingRole()">确认已分拣</el-button>
      <el-button type="primary" @click="listedBox" v-if="showListedBtn" :loading="receivedLoading">确认上架</el-button>
      <el-button type="primary" @click="offlineDeliveredBox" v-if="showOfflineDeliveredBtn" :loading="receivedLoading">确认已交付</el-button>
      <template v-if="showDeliveredBtn">
        <shipment-full-btn class="mgl10" :delivery-from="deliveryFrom" :data="data" @getData="getData"></shipment-full-btn>
      </template>
      <export-shipment-template :shipment="data" style="display: inline-block" class="mgl10 mgr10"></export-shipment-template>
      <box-p-d-f-button :data="data"></box-p-d-f-button>
      <appointment-p-d-f :data="data"></appointment-p-d-f>
    </footer-nav>
  </div>

</template>

<script>
import {
  confirmShipment,
  deliverShipment,
  getShipmentGoodsPage,
  getShipmentInfo,
  saveShipmentBox,
  saveShipmentGoods,
  shipmentPDF,
  saveShipmentImg, getShipmentImgArr, checkShipmentGoodsOrderHidden
} from "@/api/shipment";
import ShipmentInfoView from "@/views/shipment/components/ShipmentInfoView";
import ShipmentInfoImg from "@/views/shipment/components/ShipmentInfoImg";
import {deepCopy} from "@/utils";
import ExportShipmentA4 from "@/views/shipment/components/ExportShipmentA4.vue";
import FooterNav from "@/components/Common/FooterNav.vue";
import {STATUS_CREATED, STATUS_RECEIVED, STATUS_SORTED} from "@/utils/boxLabel";
import {
  offlineShipmentFinish,
  receivedMWShipment,
  receivedShipment,
  shipmentListedBox,
  sortedShipment
} from "@/api/shipmentV2";
import {
  ABOLISHED,
  FINISHED_SHELVES,
  FINISHED_SORTING,
  OFFICIAL_DELIVERED,
  WAIT_FL_RECEIVE,
  WAIT_RECEIVE,
  WAIT_SORTING
} from "@/utils/shipment";
import {PLAN_TYPE_FL, PLAN_TYPE_MW} from "@/utils/shippingPlan";
import item from "@/layout/components/Sidebar/Item.vue";
import {isFirstLegRole, isInboundSortingRole, isMiddleRole, isOneShippingRole} from "@/utils/common";
import WSSocket from "@/views/shipment/components/WSSocket.vue";
import {EventBus} from "@/utils/eventBus";
import ShipmentFullBtn from "@/views/shipment/components/ShipmentFullBtn.vue";
import BoxPDFButton from "@/views/shipment/components/BoxPDFButton.vue";
import AppointmentPDF from "@/views/shipment/components/AppointmentPDF.vue";
import ExportShipmentTemplate from "@/views/shipment/components/ExportShipmentTemplate.vue";

export default {
  name: "shipmentInfo",
  components: {
    ExportShipmentTemplate,
    AppointmentPDF,
    BoxPDFButton,
    ShipmentFullBtn,
    WSSocket,
    FooterNav,
    ExportShipmentA4,
    ShipmentInfoView,
    ShipmentInfoImg,
  },
  watch:{
    currentContainerId(){

    }
  },
  data(){
    return {
      id: '',
      data: {
        accountList: [],
        userId: '',
        userAccount: '',
        adminAccount: '',
        adminId: '',
        confirmTime: '',
        createTime: '',
        exBoxNum: '',
        exGoodsNum: '',
        exSkuNum: '',
        remark: '',
        rlBoxNum: '',
        rlGoodsNum: '',
        rlSkuNum: '',
        shipmentNo: '',
        saveBox: 0,
        labelOrder: null, //
      },
      shipmentBox: [
      ], // 货件
      shipmentGoods: [
      ], // 商品
      shipmentGoodsApi: [],
      shipmentBoxLabelList: [], // 箱唛
      shipmentGoodsParams: {
        shipmentId: 0,
        page: 1,
        pageSize: 1000,
      },
      loading: false,
      btnLoading: false,
      boxLoading: false,
      knowSku: 0,
      printLoading: false,
      PDFDialog: false,
      jhLoading: false,
      currentPDFForm:{
        pickIds: [],
        PDFType: 1,
      },
      updateImgUrl: '',
      orderGoodsHidden: [], // 不同步的商品
      syncOrderHiddenGoods: false, // 是否把隐藏的商品显示出来
      receivedLoading: false,
      currentContainerId: '', // 当前选中的货柜id 如果是number选的是货柜 如果是字符串 选的是国内/国外
      deliveryFrom: {
        isFee: false,
        deliveryType: 'general',
      },
    }
  },
  computed:{
    accountName(){
      const accountName = [];
      this.data.accountList.forEach(item=>{
        accountName.push(item.showName)
      })
      return accountName.join('、')
    },
    checkConfirm(){
      return this.shipmentBox.some(item => typeof item.rlBoxNum  === 'undefined') || this.shipmentGoods.some(item=>{
        if(this.data.type === 1){
          return false
        }
        return item.rlGoodsNum === undefined
      })
    },
    // 当前显示的箱唛
    boxLabelList(){
      let arr = this.shipmentBoxLabelList
      if(typeof this.currentContainerId === 'number'){
        arr = arr.filter(item=> item.containerId === this.currentContainerId)
      }else if(typeof this.currentContainerId === 'string'){
        switch (this.currentContainerId){
          case STATUS_RECEIVED:
            arr = arr.filter(item=> item.isReceived === 0)
            break
          case STATUS_SORTED:
            arr = arr.filter(item=> item.isSorted === 0 && item.isReceived === 1)
            break
        }
      }
      return arr;
    },
    isFull(){
      return this.data.shipmentType === 'mkd_full' || this.data.shipmentType === 'mkd_cbt_full';
    },
    // 是否显示上架按钮
    showListedBtn(){
      // 官方仓没有上架 官方仓是已送仓/已作废
      if(this.isFull){
        return false;
      }
      if(this.data.shipmentType === 'offline_delivery'){
        return false;
      }

      if(this.boxLabelList.length === 0){
        return false
      }
      if(this.data.planType === PLAN_TYPE_MW){
        if(this.data.status2 !== FINISHED_SORTING){
          return false
        }
        // 一件代发 一件大发处理 中转由中转处理
        if(this.data.shipmentType === 'one_shipping'){
          return !!isOneShippingRole();
        }
        if(this.data.shipmentType === 'middle'){
          return !!isMiddleRole();
        }

        return false
      }

      if(this.data.planType === PLAN_TYPE_FL){
        if(this.data.status2 === FINISHED_SHELVES){
          return false
        }
        if(!this.boxLabelList.some(item => item.status === STATUS_SORTED)){
          return false
        }
        // 一件代发 一件大发处理 中转由中转处理
        if(this.data.shipmentType === 'one_shipping'){
          return !!isOneShippingRole();
        }
        if(this.data.shipmentType === 'middle'){
          return !!isMiddleRole();
        }
        return true
      }

      return false;
    },
    isSocket(){
      let flag = false
      if(isFirstLegRole()){
        if(this.data.status2 === WAIT_FL_RECEIVE){
          return true;
        }
      }
      return flag
    },
    // 展示已送仓 / 作废按钮
    showDeliveredBtn(){
      if(!this.isFull){
        return false;
      }
      if(this.data.status2 === OFFICIAL_DELIVERED || this.data.status2 === ABOLISHED){
        return false
      }
      // 如果有国内未接收 非异常箱子
      if(this.shipmentBoxLabelList.some(item => item.status === 'created' && item.isReceiveExcept === 0)){
        return false;
      }
      // 有接收了箱子 但是没装柜的
      if(this.shipmentBoxLabelList.some(item=> !item.containerId && item.isReceiveExcept === 0)){
        return false
      }

      // 所有非异常箱唛入库了 显示按钮
      const flag = this.shipmentBoxLabelList.filter(item=> item.isReceiveExcept === 0 && item.isSortingExcept === 0)
        .every(item=> item.stockStatus === 3)
      if(flag){
        return true
      }


      return false;
    },
    // 显示已送达按钮
    showOfflineDeliveredBtn(){
      // 头程、分拣运营才有权限
      if(!isFirstLegRole() && !isInboundSortingRole()){
        return false;
      }
      // 清关后都可以交付
      const arr = [
        WAIT_RECEIVE, WAIT_SORTING, FINISHED_SORTING
      ];
      if(!arr.includes(this.data.status2)){
        return false;
      }
      if(!this.data.containerList){
        return false;
      }
      if(!this.data.containerList.every(item=> arr.includes(item.status))){
        return false;
      }

      return this.data.shipmentType === 'offline_delivery'
    }
  },
  created() {
    this.id = this.$route.query.id
    this.getData()
    this.getShipmentGoodsOrderHidden()

    // 对接socket
    EventBus.$off('boxScan')
    EventBus.$on('boxScan', this.boxScan)

    // 箱唛改变
    EventBus.$off('changeBox')
    EventBus.$on('changeBox', this.getData)
  },
  methods:{
    isInboundSortingRole,
    boxScan(data){
      if(!data || !data.boxId){
        return;
      }
      const box = this.shipmentBoxLabelList.find(item => item.boxId === data.boxId)
      if(box){
        this.$successMessage(data.boxId + '扫描成功')
        this.getData(false)
      }else{
        this.$successMessage(data.boxId + '扫描成功')
        // 是其他箱唛
        this.$confirm('当前扫描箱唛非当前货件单，是否切换到对应箱唛的货件单？', '切换货件单')
          .then(()=>{
            this.$router.push({
              name: 'shipmentInfo',
              query: {
                id: data.shipmentId
              }
            })
            this.$router.go(0)
          })
          .catch(()=>{})

      }
    },
    isFirstLegRole,
    WAIT_SORTING() {
      return WAIT_SORTING
    },
    PLAN_TYPE_FL() {
      return PLAN_TYPE_FL
    },
    PLAN_TYPE_MW() {
      return PLAN_TYPE_MW
    },
    WAIT_RECEIVE() {
      return WAIT_RECEIVE
    },
    WAIT_FL_RECEIVE() {
      return WAIT_FL_RECEIVE
    },
    saveShipmentImg,
    getShipmentImgArr,
    getData(loading = true){
      this.loading = loading;
      getShipmentInfo(this.id)
        .then(res=>{
          this.loading = false;
          this.data = deepCopy(res.data)
          this.updateImgUrl = res.info.updateImgUrl
          this.shipmentBox = [];
          res.data.shipmentBox.forEach(item=>{
            // item.rlBoxNum = item.rlBoxNum === null ? undefined : item.rlBoxNum
            item.rlBoxNum = res.data.status === 0 && item.save === 0 ? item.exBoxNum : item.rlBoxNum
            this.shipmentBox.push(item)
          })

          this.shipmentBoxLabelList = res.data.boxLabelList.map(item=>{
            item.rlGoodsNum = item.rlGoodsNum === null ? item.exGoodsNum: item.rlGoodsNum
            return item
          })


          this.shipmentGoods = [];

          // 计算一共有多少页 请求数据
          this.shipmentGoodsApi = [];
          let totalPage = Math.ceil(res.info.shipmentGoodsTotal / this.shipmentGoodsParams.pageSize)
          for (let page = 1; page <= totalPage ; page++) {
            const params = {
              page: page,
              pageSize: this.shipmentGoodsParams.pageSize,
              shipmentId: this.data.id,
            }
            this.shipmentGoodsApi.push(false)
            this.getShipmentGoods(params)
          }

        })
    },
    getShipmentGoodsOrderHidden(){
      checkShipmentGoodsOrderHidden(this.id)
        .then(res=>{
          this.orderGoodsHidden = deepCopy(res.data)
        })
    },
    // 分页获取商品数据
    getShipmentGoods(params){
      this.loading = true
      getShipmentGoodsPage(params)
        .then(res=>{
          const data = []
          res.data.forEach(item=>{
            // item.rlGoodsNum = item.rlGoodsNum === null ? undefined : item.rlGoodsNum
            item.rlGoodsNum = this.data.status === 0 && !item.save ? item.exGoodsNum : item.rlGoodsNum
            item.rlGoodsBoxNum = this.data.status === 0 && !item.save ? item.exGoodsBoxNum : item.rlGoodsBoxNum
            item.rlGoodsMixinNum = this.data.status === 0 && !item.save ? item.exGoodsMixinNum : item.rlGoodsMixinNum
            // 如果是未贴标数据 显示对应的数据
            if(item.isTB && this.data.labelOrder && this.data.labelOrder.status === 2){
              item.rlGoodsNum = this.data.status === 0 && !item.save ? 0 : item.rlGoodsNum
            }
            item.isEdit = 0;
            data.push(item)
          })
          this.shipmentGoods.push(...data)
          this.shipmentGoodsApi[params.page - 1] = true
          if(this.shipmentGoodsApi.every(item => item)){
            this.loading = false
            if(this.data.status === 0){
              const flag = this.data.saveBox === 1 && this.shipmentGoods.every(item=> item.save === 1);
              if(flag){
                this.saveForShipment()
              }
            }
          }
        })
    },
    confirmTable(){
      const postData = {
        id: this.data.id,
        shipmentBox: this.shipmentBox,
        shipmentGoods: this.shipmentGoods,
        remark: this.data.remark,
        syncOrderHiddenGoods: this.syncOrderHiddenGoods
      }
      this.btnLoading = true
      confirmShipment(postData)
        .then(res=>{
          this.btnLoading = false
          if(res.error === 0){
            this.$store.dispatch('user/getInfo');
            this.$successMessage(res.message)
            this.currentPDFForm.pickIds.push(this.data.id)
            this.shipmentPDF()
            this.getData()
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 校验数量数量是否相同
    checkConfirmNum(){

      // 是否有没填写的库存
      let inventoryLocationFlag = false
      this.shipmentGoods.forEach(item=>{
        if (item.inventoryLocation === '') {
          inventoryLocationFlag = true
        }
      })

      // 是否前后数量一致
      const flag = this.shipmentBox.every(item => item.rlBoxNum  === item.exBoxNum) && this.shipmentGoods.every(item=>{
        if(this.data.type === 1){
          return true
        }
        return item.rlGoodsMixinNum === item.exGoodsMixinNum && item.rlGoodsBoxNum === item.exGoodsBoxNum
      })

      // 地狱回调 -> 链式调用
      new Promise((resolve, reject) => {
        resolve()
      })
        // 实际入库数量和预计入库数量是否相等
        .then(()=>{
          return new Promise((resolve, reject)=>{
            if(flag){
              resolve()
              return;
            }
            setTimeout(()=>{
              this.$alert(
                `<p><span style="color: #FF0000">${this.$t('shipment.confirmText1')}</span></p>`,
                this.$t('shipment.saveInfoTitle'),
                {
                  dangerouslyUseHTMLString:true,
                  // type:'warning',
                  showCancelButton:true,
                }
              )
                .then(res=>{
                  resolve()
                })
                .catch(res=>{
                  reject()
                })
            },0)
          })
        })
        // 是否存在未配置的库位的商品
        .then(()=>{
          return new Promise((resolve, reject)=>{
            if(!inventoryLocationFlag){
              resolve()
              return;
            }
            setTimeout(()=>{
              this.$alert(
                `<p>${this.$t('table.inventoryLocation.当前入库商品存在尚未配置库位的SKU，确定要操作入库吗？')}</p><p>${this.$t('table.inventoryLocation.如不配置，入库后您也可以在库存列表继续操作配置库位')}</p>`,
                this.$t('shipment.saveInfoTitle'),
                {
                  dangerouslyUseHTMLString:true,
                  // type:'warning',
                  showCancelButton:true,
                }
              )
                .then(res=>{
                  resolve()
                })
                .catch(res=>{
                  reject()
                })
            },0)

          })
        })
        // 是否开启商品同步
        .then(()=>{
          return new Promise((resolve,reject)=>{
            if(this.orderGoodsHidden.length === 0){
              resolve()
              return;
            }
            setTimeout(()=>{
              const title = this.$t('部分SKU未开启订单同步')
              let message = `<p>当前入库SKU:<p>`
              this.orderGoodsHidden.forEach(item=>{
                message += `<p class="font-warning">${item.sku}</p>`
              })
              message += `<p>${this.$t('尚未开启订单同步，如该SKU入库后开始售卖，请及时设置开启同步该SKU订单')}</p>`
              this.$alert(
                message,
                title,
                {
                  dangerouslyUseHTMLString:true,
                  // type:'warning',
                  showCancelButton:true,
                  cancelButtonText: '仅入库',
                  confirmButtonText: '入库并开启',
                }
              )
                .then(res=>{
                  this.syncOrderHiddenGoods = true
                  resolve()
                })
                .catch(res=>{
                  // 取消也要入库
                  resolve()
                })
            }, 0)
          })
        })
        .then(()=>{
          this.confirmTable()
        })
        .catch(res=>{
          console.log('catch')
          console.log(res)
        })
    },
    // 确认送仓
    deliver(){
      this.$alert(
        `<p><span style="color: #FF0000">${this.$t('shipment.deliveryText1')}</span></p>`,
        this.$t('shipment.deliveryTitle'),
        {
          dangerouslyUseHTMLString:true,
          // type:'warning',
          showCancelButton:true,
        }
      )
        .then(res=>{
          this.btnLoading = true
          deliverShipment(this.data.id)
            .then(_res=>{
              this.btnLoading = false
              if(_res.error === 0){
                this.$successMessage(_res.message)
                this.$store.dispatch('user/getInfo');
                this.goBack()
              }else{
                this.$errorMessage(_res.message)
              }
            })

        })
        .catch(res=>{

        })
    },
    goBack(){
      this.$router.go(-1)
    },
    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }){
      if(this.data.status === 0 && this.data.saveBox === 0){
        if (columnIndex === 3) {
          return [2, 1];
        }
      }

    },
    showSaveBox(){
      // 判断入库数是否相同
      const flag = this.shipmentBox.every(item => item.rlBoxNum  === item.exBoxNum);
      let html = `
        <p><span style="color: #FF0000">${this.$t('shipment.saveBoxText1')}</span></p>
        <p><span style="color: #FF0000">${this.$t('shipment.saveBoxText2')}</span></p>
        <p><span>${this.$t('shipment.saveBoxText3')}</span></p>
      `;
      if(!flag){
        html = `
          <p style="margin-bottom: 20px"><span style="color: #FF0000;">${this.$t('shipment.saveBoxText4')}</span></p>
        ` + html;
      }

      this.$alert(
        html,
        this.$t('shipment.saveBoxTitle'),
        {
          dangerouslyUseHTMLString:true,
          // type:'warning',
          showCancelButton:true,
        }
      )
        .then(res=>{
          //
          this.saveBox()
        })
        .catch(res=>{

        })
    },
    // 单独保存箱子
    saveBox(){
      this.boxLoading = true;
      const data = {
        id: this.id,
        shipmentBox: this.shipmentBox,
      }
      saveShipmentBox(data)
        .then(res=>{
          this.boxLoading = false;
          if(res.error === 0){
            this.$successMessage(res.message)
            this.getData()
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 修改商品数
    editGoodsNum(row){
      row.isEdit = 1;
      setTimeout(()=>{
        this.$refs['goods'+row.id].focus();
      },0)
    },
    // 保存实际入库数量
    saveGoodsNum(row){
      if(row.exGoodsNum !== row.rlGoodsNum && !this.knowSku){
        const html = `
       <p><span style="color: #ff0000">${this.$t('shipment.saveSKUText1')}</span></p>
       <p style="margin-top: 20px"><span>${this.$t('shipment.saveSKUText2')}</span></p>
      `;
        this.$alert(
          html,
          this.$t('shipment.saveSKUTitle'),
          {
            dangerouslyUseHTMLString:true,
            // type:'warning',
            showCancelButton:true,
          }
        )
          .then(res=>{
            //
            this.saveGoodsNumStep2(row)
            this.knowSku = 1
          })
          .catch(res=>{

          })
      }else{
        this.saveGoodsNumStep2(row)
      }

    },
    saveGoodsNumStep2(row){
      const data = {
        id: row.id,
        rlGoodsNum: row.rlGoodsNum,
      }
      saveShipmentGoods(data)
        .then(res=>{
          if(res.error === 0){
            this.$successMessage(res.message)
            this.getData()
          }else{
            this.$errorMessage(res.messag)
          }
        })
    },
    // 全部都入库了 判断是否入库
    saveForShipment(){
      this.$alert(
        `<p>${this.$t('shipment.saveInfoText1')}</p>`,
        this.$t('shipment.saveInfoTitle'),
        {
          dangerouslyUseHTMLString:true,
          // type:'warning',
          showCancelButton:true,
        }
      )
        .then(res=>{
          //
          this.confirmTable()
        })
        .catch(res=>{

        })
    },

    showPDFDialog(row = null){
      this.currentPDFForm.pickIds = [];
      this.currentPDFForm.pickIds.push(row.id)
      this.PDFDialog = true
    },

    shipmentPDF(){
      this.printLoading = true;
      shipmentPDF(this.currentPDFForm)
        .then(res=>{
          this.printLoading = false;
          if(res.type === 'application/json'){
            this.$errorMessage('系统繁忙，请稍后再试');
            // this.$errorMessage('功能开发中...');
            return;
          }
          this.PDFDialog = false;
          this.currentPDFForm.pickIds = [];
          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );
          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000 * 5)

        })
    },
    // 确认接收 (国内接收)
    confirmReceived(){
      new Promise((resolve, reject)=>{
        const flag = this.shipmentBoxLabelList.every(item=> item.status === STATUS_RECEIVED)
        if(flag){
          resolve()
          return;
        }
        let title = '确认接收？';
        let message = '存在待接收状态的货件，确认当前货件单的货件已全部接收完毕？'
        this.$confirm(message, title)
          .then(()=>{
            resolve()
          })
          .catch(()=>{
            reject()
          })
      })
        .then(()=>{
          this.receivedLoading = true
          const data = {
            id: this.data.id,
            boxLabelList: this.shipmentBoxLabelList,
          }
          receivedShipment(data)
            .then(res=>{
              this.receivedLoading = false
              if(res.error === 0){
                this.getData()
                this.$successMessage(res.message)
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
    },
    // 确认接收 （海外）
    confirmWMReceived(){
      new Promise((resolve, reject)=>{
        let title = '确认接收？';
        this.$confirm('',title)
          .then(()=>{
            resolve()
          })
          .catch(()=>{
            reject()
          })
      })
        .then(()=>{
          const data = {
            id: this.data.id,
          }
          this.receivedLoading = true
          receivedMWShipment(data)
            .then(res=>{
              this.receivedLoading = false
              if(res.error === 0){
                this.getData()
                this.$successMessage(res.message)
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
    },
    // 确认已分拣 （海外）
    confirmSorted(){
      new Promise((resolve, reject)=>{
        const flag = this.boxLabelList.every(item=> item.status === STATUS_SORTED)
        const set = new Set();
        this.boxLabelList.forEach(item=> {
          if(item.status !== STATUS_SORTED){
            set.add(item.boxId)
          }
        })
        const num = set.size
        let message = '';
        if(!flag){
          message += `<div class="font-red">未分拣箱数：${num}</div>`
          message += '<div class="font-red">确认本单货件已扫描分拣完毕？“待分拣”状态的货件代表货件未收到/丢失，不会计入库存，后续也不能再操作上架</div>';
        }
        let title = '确认已分拣'
        this.$confirm(message, title, {
          dangerouslyUseHTMLString:true,
        })
          .then(()=>{
            resolve()
          })
          .catch(()=>{
            reject()
          })
      })
        .then(()=>{
          const data = {
            shipmentId: this.data.id,
            boxList: this.boxLabelList.map(item=>{
              return {
                boxId: item.boxId,
                status: item.status
              }
            }),
          }
          sortedShipment(data)
            .then(res=>{
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{})
    },
    // 确认上架
    listedBox(){
      new Promise((resolve, reject)=>{
        this.$confirm('', '确认上架？')
          .then(()=>{
            resolve()
          })
          .catch(()=>{
            reject()
          })
      })
        .then(()=>{
          return new Promise((resolve,reject)=>{
            if(this.orderGoodsHidden.length === 0){
              resolve()
              return;
            }
            if(this.data.shipmentType !== 'one_shipping' && this.data.shipmentType !== 'middle'){
              resolve()
              return;
            }
            setTimeout(()=>{
              const title = this.$t('部分SKU未开启订单同步')
              let message = `<p>当前上架SKU:<p>`
              this.orderGoodsHidden.forEach(item=>{
                message += `<p class="font-warning">${item.sku}</p>`
              })
              message += `<p>尚未开启订单同步，如该SKU上架后开始售卖，请及时设置开启同步该SKU订单</p>`
              this.$alert(
                message,
                title,
                {
                  dangerouslyUseHTMLString:true,
                  // type:'warning',
                  showCancelButton:true,
                  cancelButtonText: '仅上架',
                  confirmButtonText: '上架并开启',
                }
              )
                .then(res=>{
                  this.syncOrderHiddenGoods = true
                  resolve()
                })
                .catch(res=>{
                  // 取消也要入库
                  resolve()
                })
            }, 0)
          })
        })
        .then(()=>{
          this.receivedLoading = true
          const data = {
            id: this.data.id,
            boxData: [],
            syncOrderHiddenGoods: this.syncOrderHiddenGoods,
          }
          this.boxLabelList.filter(item => item.status === STATUS_SORTED)
            .forEach(item=>{
              data.boxData.push({
                id: item.id,
                boxId: item.boxId,
                rlGoodsNum: item.rlGoodsNum ? item.rlGoodsNum : 0,
              })
            })
          // 确认上架
          shipmentListedBox(data)
            .then(res=>{
              this.receivedLoading = false
              if(res.error === 0){
                this.getData()
                this.$successMessage(res.message)
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{})



    },
    offlineDeliveredBox(){
      new Promise((resolve, reject)=>{
        this.$confirm('确认当前货件单的所有货件已交付完毕？', '确认已交付？')
          .then(()=>{
            resolve()
          })
          .catch(()=>{
            reject()
          })
      })
        .then(()=>{
          this.receivedLoading = true
          // 确认上架
          offlineShipmentFinish(this.data.id)
            .then(res=>{
              this.receivedLoading = false
              if(res.error === 0){
                this.getData()
                this.$successMessage(res.message)
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
    }
  },
  beforeDestroy() {
    EventBus.$off('boxScan')
  },
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px 80px;
  .header{
    //display: flex;
    //justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .header-card{
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
}
.goods-table{
  width: 1500px;
  .goods-title{
    font-size: 14px;
  }
  .goods-attr{
    font-size: 13px;
    color: #7F7F7F;
  }
}
.table-tips{

}
</style>
